package com.cn.jinl.service;

import com.cn.jinl.api.IProcureService;
import com.cn.jinl.api.IProcureStorageService;
import com.cn.jinl.dao.ProcureMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class ProcureServiceImpl implements IProcureService {

    @Autowired
    private ProcureMapper procureMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private IProcureStorageService procureStorageService;

    @Override
    public List<Procure> getProcureTaskList(QueryForm queryForm) throws Exception {
        String procureStatus = queryForm.getProcureStatus();
        if(StringUtils.equals("0",procureStatus)){
            queryForm.setProcureStatus("");
            queryForm.setDoubleProcureStatus("1");
        }
        int count = procureMapper.selectProcureListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<Procure> procures = procureMapper.selectProcureList(queryForm);
        procures.get(0).setCount(count);
        for(Procure procure:procures){
            List<ProcureStorage> procureStorages = procure.getProcureStorages();
            List<ProcureClose> procureCloses = procure.getProcureCloses();
            procure.setMaterialCount(procureStorages.size());
            double totalMoney = 0.0;
            for(ProcureClose procureClose:procureCloses){
                String money = procureClose.getClosePayMoney();
                totalMoney+= Double.parseDouble(money);
            }
            String money = NumberUtil.getPoint(totalMoney,1);
            procure.setHasPayMoney(money);
            double left = Double.parseDouble(procure.getTotalMoney()) - totalMoney;
            String leftStr = NumberUtil.getPoint(left,1);
            procure.setNoPayMoney(leftStr);
        }
        return procures;
    }

    @Override
    public String addProcure(Procure procure) throws Exception {
        List<ProcureStorage> procureStorages = procure.getProcureStorages();
        if(CollectionUtils.isEmpty(procureStorages)){
            return "参数错误!";
        }

        String id = CommonUtil.generateRandomNum("procure_");
        procure.setId(id);
        procure.setProcureStatus("0");
        double allTotal = 0.0;
        for(ProcureStorage procureStorage:procureStorages){
            procureStorage.setProcureId(id);
            procureStorage.setProcureExistCount("0");
            String procureCount = procureStorage.getProcureCount();
            String procurePrice = procureStorage.getProcurePrice();
            double total = Double.parseDouble(procureCount)*Double.parseDouble(procurePrice);
            String totalNum = NumberUtil.getPoint(total,1);
            allTotal +=total;
            procureStorage.setProcureTotalPrice(totalNum);
        }
        String allTotalStr = NumberUtil.getPoint(allTotal,1);
        String key = "C"+generateUUID.getYearMoth();
        int num = generateUUID.getNumberFlag(key);
        String code = key+generateUUID.getThreeNumStr(num);
        procure.setProcureCode(code);
        procure.setTotalMoney(allTotalStr);
        int count = procureMapper.insertSelective(procure);
        if(count < 1){
            return "插入表异常！";
        }
        String resp = procureStorageService.batchAddProcureStorages(procureStorages);
        if(!StringUtils.isEmpty(resp)){
            throw new Exception(resp);
        }
        return "";
    }

    @Override
    public String updateProcure(Procure procure) throws Exception {
        return null;
    }

    @Override
    public String updateDisProcure(Procure procure) throws Exception {
        String id =  procure.getId();
        Procure exist = procureMapper.selectByPrimaryKey(id);
        if(exist == null){
            return "任务不存在！";
        }
        if(!StringUtils.equals("0",exist.getProcureStatus())){
            return "任务不在待入库状态，无法取消！";
        }

        if(StringUtils.equals("1",exist.getPayStatus())){
            return "已经支付，无法取消";
        }
        Procure update = new Procure();
        update.setProcureStatus("4");
        update.setId(id);
        int count = procureMapper.updateByPrimaryKeySelective(update);
        if(count < 0){
            return "更新任务表异常！";
        }
        String resp = procureStorageService.updateProcureStorageStatusByProcId(id,"3");
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updateCompletePayProcure(Procure procure) throws Exception {
        String id = procure.getId();
        if(StringUtils.isEmpty(id)){
            return "参数异常！";
        }
        Procure update = new Procure();
        update.setRemark(procure.getRemark());
        update.setPayStatus("1");
        update.setProcureStatus("3");
        update.setSurePayUser(procure.getSurePayUser());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sureTime = simpleDateFormat.format(new Date());
        update.setSurePayTime(sureTime);
        ProcureExample example = new ProcureExample();
        example.createCriteria().andIdEqualTo(id);
        Procure exist = procureMapper.selectByPrimaryKey(id);

        if(null == exist){
            return "采购不存在！";
        }
        if(StringUtils.equals(exist.getPayStatus(),"1")){
            return "采购支付异常，请检查采购支付状态！";
        }

        int count = procureMapper.updateByExampleSelective(update,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, Object> getAPIProcureTasks(QueryForm queryForm) throws Exception {
        int waitingStorageCount = 0;
        int storagingCount = 0;
        ProcureExample example = new ProcureExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andProcureStatusEqualTo("0");
        waitingStorageCount = procureMapper.countByExample(example);

        ProcureExample example1 = new ProcureExample();
        example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andProcureStatusEqualTo("1");
        storagingCount =  procureMapper.countByExample(example1);

        int count = procureMapper.selectProcureListCount(queryForm);
        List<Procure> procures = procureMapper.selectProcureList(queryForm);
        for(Procure procure:procures){
            List<ProcureStorage> procureStorages = procure.getProcureStorages();
            procure.setMaterialCount(procureStorages.size());
        }
        Map<String,Object> maps = Maps.newHashMap();
        maps.put("waitingStorageCount",waitingStorageCount);
        maps.put("storagingCount",storagingCount);
        maps.put("totalCount",count);
        maps.put("list",procures);
        return maps;
    }

    @Override
    public List<Procure> getProcureTaskingList() throws Exception {
        List<Procure> procures = procureMapper.selectProcuringList();
        return procures;
    }
}
